package com.cssw.fyzb.busi.api.live;

import com.cssw.fyzb.core.model.vo.live.AnchorVo;
import com.cssw.fyzb.busi.service.live.AnchorService;
import com.cssw.fyzb.busi.service.live.LiveService;
import com.cssw.fyzb.core.model.dodb.CmfLive;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.cssw.fyzb.busi.util.Bizs.*;
import static com.cssw.fyzb.busi.util.Const.LIVE_IDLE;

/**
 * @author Feng Chen
 */
@Function(description = "退出直播间", parameters = {
        @Parameter(name = "userId", type = Type.Integer, description = "用户标识", required = true),
        @Parameter(name = "liveId", type = Type.String, description = "房间标识", required = true),
})
@Component
public class DropLiveRoom implements Action {

    @Autowired
    private LiveService liveService;

    @Autowired
    private AnchorService anchorService;

    private static final Logger logger = LoggerFactory.getLogger(DropLiveRoom.class);

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        Long liveId = request.getLong("liveId");

        try {

            AnchorVo anchor = anchorService.queryAnchorByUserId(userId);

            // 非主播
            if (anchor == null) {
                return Response.fail(ERROR_LIVE_NOT_ANCHOR.message, ERROR_LIVE_NOT_ANCHOR.code);
            }

            // 直播间不存在
            CmfLive live = liveService.findByLiveId(liveId);
            if (live == null) {
                return Response.fail(ERROR_LIVE_UNKNOWN_ROOM.message, ERROR_LIVE_UNKNOWN_ROOM.code);
            }

            // 直播间已关闭
            if (LIVE_IDLE.equals(anchor.getLive()) || LIVE_IDLE.equals(live.getStatus())) {
                return Response.fail(ERROR_LIVE_CLOSED_ROOM.message, ERROR_LIVE_CLOSED_ROOM.code);
            }

            liveService.dropRoom(anchor.getAnchorId(), liveId);

            return Response.success();
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("操作异常");
        }

    }

}
